import {
  FC,
  PropsWithChildren,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react';
import HeaderBar from './headerCom';
import { chatDetail } from '@/request';
import { type CHAT_DETAIL_TYPE } from '@/request';
import MessageBlock from './messageBlock';
import { WrapContext } from './wrap';

const Chat: FC<PropsWithChildren> = (props) => {
  // 获取顶部参数
  const [message, setMessage] = useState<CHAT_DETAIL_TYPE['messages']>([]);
  const context = useContext(WrapContext);
  const problem_id = context?.problem_id;

  // 接收来自inputCom输入框的数据
  const receiveInput = useCallback((msg: unknown) => {
    if (msg && typeof msg === 'string') {
      setMessage((prev) => {
        // 前端自行拼接
        return [...prev, { role: 'user', content: msg }];
      });
    }
  }, []);
  context?.event.onListen<string>('input-msg', receiveInput);

  // 接收来自websocket的消息
  const receiveWS = useCallback(
    (msg: unknown) => {
      console.log(msg, 'chatroom-msg数据');
      const _msg = msg as unknown as RECE_MSG_TYPE;
      // 聊天消息处理
      if (_msg.topic === 'chat') {
        setMessage((prev) => {
          // 前端自行拼接
          return [
            ...prev,
            { role: _msg.data.role, content: _msg.data.content },
          ];
        });
        // 解题阶段更新
      } else if (_msg.topic === 'context') {
        if (_msg.data.stage !== undefined) {
          context?.setStage(_msg.data.stage);
        }
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [context?.setStage],
  );

  context?.ws?.addEvent(receiveWS);
  // 获取数据
  const getData = useCallback(() => {
    if (problem_id) {
      chatDetail({ problem_id }).then((res) => {
        setMessage(res.messages);
        context?.setChatDetail(res);
        context?.setStage(res.stage);
      });
    }
  }, [problem_id, context]);
  // 获取数据
  useEffect(() => {
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // 自动滚动到底部
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (ref.current?.scrollTop !== undefined) {
      ref.current.scrollTop = ref.current?.scrollHeight;
    }
  }, [message]);
  return (
    <div className='bg-title flex flex-col rounded-large grow shrink-0 overflow-hidden border-[#DADADA] rounded-[8px]'>
      <HeaderBar
        title='讨论'
        path={new URL('@/assets/imgs/icon-question.png', import.meta.url).href}
      />
      <div ref={ref} className='bg-white grow shrink basis-1 overflow-auto'>
        {message.map((item, index) => (
          <MessageBlock key={index} item={item} />
        ))}
      </div>
      {props.children}
    </div>
  );
};

export default Chat;
